package com.bawei.mine.vm

import androidx.lifecycle.viewModelScope
import com.bawei.common.vm.BaseViewModel
import com.bawei.mine.entity.Data
import com.bawei.mine.intent.MineViewIntent
import com.bawei.mine.model.MineRepository
import com.bawei.mine.state.MineUIState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class MineViewModel  @Inject constructor(private val mineRepository: MineRepository)  :BaseViewModel<MineViewIntent>(){


    private val _uiState =MutableStateFlow<MineUIState>(MineUIState.LoadEmpty)
    val uiState :StateFlow<MineUIState> =_uiState.asStateFlow()
    override fun dispatchIntent(intent: MineViewIntent) {

        when(intent){
            is MineViewIntent.loadGoodsAllOrder ->loadAllOrders(intent.category_id,intent.currentPage,intent.pageSize)
        }
    }

    private fun loadAllOrders(category_id :Int ,currentPgae :Int ,pageSize:Int) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                mineRepository.loadAllOrders(category_id,currentPgae,pageSize).collect{
                    withContext(Dispatchers.Main){
                        if (it.isNotEmpty()){
                            _uiState.value = MineUIState.LoadOrderAllSuccess(it)
                        }else {
                            _uiState.value = MineUIState.LoadOrderAllFailed("code Error ！")
                        }

                    }
                }

            }catch (e:Exception){
                e.printStackTrace()
                withContext(Dispatchers.Main){
                    _uiState.value = MineUIState.LoadOrderAllFailed("订单接口异常")
                }
            }finally {
                cancel()
            }
        }
    }

}